<template>
  <Form
    :label-width="80"
    :model="model"
    :rules="rules"
    ref="modelForm"
  >
    <template
      v-for="(item, index) in formOptions"
      :key="index"
    >
      <FormItem
        :label="item.label"
        :prop="item.prop"
        v-if="!item.children"
      >
        <template v-if="item.prop === 'daterange'">
          <component
            :type="item.prop"
            v-model="model[item.prop!]"
            :placeholder="item.placeholder"
            :is="`${item.type}`"
            v-bind="item.attrs"
          ></component>
        </template>
        <template v-else>
          <component
            v-model="model[item.prop!]"
            :placeholder="item.placeholder"
            :is="`${item.type}`"
            v-bind="item.attrs"
          ></component>
        </template>
      </FormItem>
      <FormItem
        :label="item.label"
        :prop="item.prop"
        v-else
      >
        <component
          v-model="model[item.prop!]"
          :placeholder="item.placeholder"
          :is="`${item.type}`"
          v-bind="item.attrs"
        >
          <component
            v-for="(child, index) in item.children"
            :key="index"
            :value="child.value"
            :label="child.label"
            :is="`${child.type}`"
            v-bind="child.attrs"
          ></component>
        </component>
      </FormItem>
    </template>
    <FormItem>
      <slot
        name="action"
        :modelForm="modelForm"
        :model="model"
      ></slot>
    </FormItem>
  </Form>
</template>

<script setup lang="ts">
import { FormOptions } from './types'
import { PropType, ref } from 'vue'
import { cloneDeep } from 'lodash'
import { FormItem } from 'view-ui-plus'

const props = defineProps({
  formOptions: {
    type: Array as PropType<FormOptions[]>,
    required: true
  }
})

//  定义form ref
const modelForm = ref<any>({})

// 表单model
const model = ref<any>({})
// 表单验证规则
const rules = ref<any>({})

// 不能放到mounted中会导致页面加载直接触发一次验证
if (props.formOptions && props.formOptions.length) {
  let m: any = {}
  let r: any = {}
  props.formOptions.map((item) => {
    m[item.prop!] = item.value
    r[item.prop!] = item.rules
  })
  model.value = cloneDeep(m)
  rules.value = cloneDeep(r)
}

// 自定义一个清空表单
const resetForm = () => {
  modelForm.value.resetFields()
  if (props.formOptions && props.formOptions.length) {
    props.formOptions.map((item) => {
      if (item.type === 'datePicker') {
        model.value.daterange = []
      }
    })
  }
}

// 自定义一个表单验证
const validateForm = () => {
  return modelForm.value.validate
}

// 暴露form组件
defineExpose({
  resetForm,
  validateForm
})
</script>

<style>
.ivu-radio {
  line-height: inherit;
}
</style>
